
import 'dart:convert';

import 'package:data_table_2/data_table_2.dart';
import 'package:flutter/material.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:yuellyfactory/util/ToastUtil.dart';
import 'package:yuellyfactory/views/dto/PricePart.dart';

import '../../eventbus/EventBusUtil.dart';
import '../../eventbus/EventRefreshBase.dart';
import '../../util/BaseRequest.dart';
import '../../util/ColorUtil.dart';
import '../../util/MathUtil.dart';
import '../../util/ViewUtil.dart';
import '../dto/PriceSerial.dart';


class MaterialAddVC extends StatefulWidget {
  final VoidCallback callback;
  final PricePart pricePart;
 // final PriceSerial serial;
  const MaterialAddVC({super.key, required this.callback, required this.pricePart});

  @override
  State<MaterialAddVC> createState() => _MaterialAddVCState();
}

class _MaterialAddVCState extends State<MaterialAddVC> {

  final popoverController = ShadPopoverController();
  final formKey = GlobalKey<ShadFormState>();
  var specsList=[];
  PricePart pricePart=PricePart();

  final dialogKey = GlobalKey<ShadFormState>();
  //系列
  //Map idNams={};
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

  }

  @override
  Widget build(BuildContext context) {
    return
      ShadSheet(
      onClosing: (){
        widget.callback();
      },
      constraints: const BoxConstraints(minWidth: 800,maxWidth: 800),

        title: Row(
          children: [
            const Text('型号添加'),
            const SizedBox(width: 50,),
            ViewUtil.doneIcon("保存", (){
              save();
            })
          ],
        ),
      child: ShadForm(
        key: formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [


            const SizedBox(height: 16),

            Row(children: [
              Expanded(child:  ShadInputFormField(
                id: 'name',

                label: const Text('型号名称'),
                placeholder: const Text('请输入型号名称'),
                validator: (v) {
                  if (v.isEmpty) {
                    return '请输入型号名称';
                  }
                  return null;
                },
              ),),
              const SizedBox(width: 10),
              Expanded(child: ShadInputFormField(
                id: 'code',
                label: const Text('Code'),

                placeholder: const Text('请输入Code'),
                validator: (v) {
                  if (v.isEmpty) {
                    return '请输入Code';
                  }
                  return null;
                },
              ),)
            ],),
            const SizedBox(height: 16),
            Row(
              children: [
                Expanded(child: ShadInputFormField(
                  id: 'dPrice',
                  label: const Text('单价'),
                  suffix: const Text('元'),
                  initialValue: "0",
                  placeholder: const Text('请输入单价'),
                  validator: (v) {
                    if (v.isEmpty) {
                      return '请输入单价';
                    }
                    return null;
                  },
                ),),
                const SizedBox(width: 10),
                Expanded(child: ShadInputFormField(
                  id: 'tax',
                  label: const Text('税点(如8%,则填写0.08）'),
                  suffix: const Text('%'),
                  initialValue: "0",
                  placeholder: const Text('请输入税点'),
                  validator: (v) {
                    if (v.isEmpty) {
                      return '请输入税点';
                    }
                    return null;
                  },
                ),)
              ],

            ),
            const SizedBox(height: 16),
            Row(
              children: [
                Text('型号说明',style: TextStyle(color: Colors.black,  fontSize: ViewUtil.fontSize(22)),),
                Expanded(child: Container()),
                ViewUtil.addIcon('新增型号说明',(){
                  showSpecDialog({"name":"","value":""});
                }),
              ],
            ),
            const SizedBox(height: 16),
            specView(),
            const SizedBox(height: 16),


          ],

        ),

      ),
    );
  }


  Widget specView(){

    final double tableHeight = _calculateTableHeight(specsList.length);
    return // 表格（高度固定为计算值）
      Padding(
        padding: EdgeInsets.symmetric(horizontal: _outerPadding),
        child: Container(
          // 应用计算出的高度
          height: tableHeight,
          decoration: BoxDecoration(
            border: Border.all(color: Colors.grey[200]!, width: _borderWidth),
            borderRadius: BorderRadius.circular(8),
          ),
          child: DataTable2(
            columnSpacing: 12,
            //  minWidth: MediaQuery.of(context).size.width - 2 * _outerPadding,
            minWidth: 500,
            headingRowHeight: _headerHeight - 2 * _borderWidth, // 减去边框占用高度
            dataRowHeight: _rowHeight - 2 * _borderWidth, // 减去边框占用高度
            // 表头
            columns: const [
              DataColumn2(
                label: Text('  操作'),
                fixedWidth: 140,
              ),
              DataColumn2(
                label: Text('名称'),
                size: ColumnSize.L,

              ),
              DataColumn2(
                label: Text('参数'),
                size: ColumnSize.L,
              ),
            ],

            // 表格内容（行高固定）
            rows: specsList.map((item) {
              return DataRow(cells: [
                DataCell(
                  Row(
                    children: [
                      ViewUtil.editIcon('编辑规格',(){showSpecDialog(item);}),
                      ViewUtil.delIcon('删除规格',(){
                        specsList.remove(item);
                        setState(() {

                        });
                      }),

                    ],
                  ),
                   ),
                DataCell(Padding(
                  padding: const EdgeInsets.symmetric(vertical: 12),
                  child: Text(item["name"]),
                )),

                DataCell(Padding(
                  padding: const EdgeInsets.symmetric(vertical: 12),
                  child: Text(item["value"]),
                )),

              ]);
            }).toList(),
          ),
        ),
      );
  }

  // 固定高度参数（可根据需求调整）
  final double _headerHeight = 56; // 表头高度（含内边距）
  final double _rowHeight = 48; // 每行高度（含内边距）
  final double _borderWidth = 1; // 边框宽度
  final double _outerPadding = 10; // 表格外间距

  // 计算表格总高度的核心方法
  double _calculateTableHeight(int length) {
    // 总高度 = 表头高度 + 数据行总高度 + 边框总高度
    // 边框高度：上下边框（2条）+ 行之间的分隔线（数据行数-1条）
    final int borderCount = 2 + (length - 1);
    final double totalBorderHeight = borderCount * _borderWidth;

    return _headerHeight + // 表头高度
        (_rowHeight * length) + // 所有数据行高度
        totalBorderHeight; // 边框总高度
  }



  void showSpecDialog(var item){
    showShadDialog(context: context, builder: (context)=>
        ShadDialog(
            actions: [ShadButton(child: const Text('确定'),onPressed: (){
                  if (dialogKey.currentState!.saveAndValidate()) {
                    var values = dialogKey.currentState!.value;
                    var name=values["name"];
                    var value=values["value"];
                    if(item["name"].length==0){
                      item["name"]=name;
                      item["value"]=value;
                      specsList.add(item);

                    }else{
                      item["name"]=name;
                      item["value"]=value;
                    }
                    setState(() {

                    });
                    Navigator.pop(context);
                  }
            },)],
            child:
            ShadForm(
              key: dialogKey,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  ShadInputFormField(
                    id: 'name',
                    initialValue: item["name"],
                    label: const Text('规格名称'),
                    placeholder: const Text('请输入规格名称'),
                    validator: (v) {
                      if (v.isEmpty) {
                        return '请输入规格名称';
                      }
                      return null;
                    },
                  ),
                  const SizedBox(height: 16),
                  ShadInputFormField(
                    id: 'value',
                    initialValue: item["value"],
                    label: const Text('规格'),
                    placeholder: const Text('请输入规格'),
                    validator: (v) {
                      if (v.isEmpty) {
                        return '请输入规格';
                      }
                      return null;
                    },
                  )


                ],
              )

              ,)

        )
    );
  }

  void save(){
    if (formKey.currentState!.saveAndValidate()) {

      // if(specsList.isEmpty){
      //   ToastUtil.showToast("请添加规格");
      //   return;
      // }
      var values = formKey.currentState!.value;
      var name=values["name"];
      var code=values["code"];
      var dPrice=values["dPrice"];
      var tax=values["tax"];
      String jsonString = jsonEncode(specsList);
      var parm={
        "name":name,
        "code":code,
        "spec":jsonString,
        "parentId":widget.pricePart.parentId,
        "dPrice":dPrice,
        "serialId":widget.pricePart.id,
        "tax":tax,
      };
      BaseRequest.postHttp("price/editmatterial",parameters: parm, canTip: true, context: context, onSuccess: (data){
        bool result=BaseRequest.chekResponse(data, true);
        if(result){
          ToastUtil.showToast("编辑成功");
          eventBus.fire(EventRefreshBase());
          Navigator.pop(context);
        }
      }, onError: (error){

      });

    }


  }
}
